'''
Created on Dec 6, 2009

@author: bodnaria
'''

import cgi
import hashlib
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from error import UserError
from model.User import getUserByUsername
import appengine_utilities.sessions
import os
from util import AuthorizedPage

class LoginPage(AuthorizedPage):
    
    def get(self):
        session = appengine_utilities.sessions.Session()
        if session.has_key("username"):
            self.redirect('/home')
            
        messages = {"badlogin" : "Invalid username or password.", 
                    "badEmail":"Invalid email", 
                    "badUsername": "Username not available.",
                    "badHash": "We could not  recognize the referenced link.",
                    "badSecondEmail": "Email is already in use",
                    "checkEmail": "Please follow the link sent to your email address to validate the new account."}
        
        self.outputUnauthorizedHeader()
        
        error = self.request.get("error")
        templatePath = os.path.join(os.path.dirname(__file__), 'login.html')
        if not error in messages.keys():
            message = ""
        else:
            message = messages[error]
        self.response.out.write(template.render(templatePath, {"error" : message })) 
    
    def post(self):
        username = cgi.escape(self.request.get("username"))
        password = cgi.escape(self.request.get("password"))
        hashed_password = hashlib.sha256(password).hexdigest()
        
        try:
            user = getUserByUsername(username)
            if user.password == hashed_password:
                session = appengine_utilities.sessions.Session()
                session["username"] = username
                self.redirect('/home')
                return
            else:
                raise UserError.UserError ("error")
        except UserError.UserError, e:
            self.redirect('/?error=badlogin')
            return 
        
        
        
        
